package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.PermissionDao;
import com.itheima.dao.RoleDao;
import com.itheima.dao.UserDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import com.itheima.utils.DateUtils;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Service(interfaceClass = UserService.class)
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private PermissionDao permissionDao;

    @Override
    public User findByUsername(String username) {
        User user = userDao.findByUsername(username);
        if(user != null){
            Integer id = user.getId();
            Set<Role> roles = roleDao.findByUserId(id);
            for (Role role : roles) {
                Integer roleId = role.getId();
                Set<Permission> permissions = permissionDao.findByRoleId(roleId);
                if(permissions != null && permissions.size() > 0){
                    role.setPermissions(permissions);
                }
            }
            user.setRoles(roles);
        }
        return user;
    }

    // 查询用户数据的分页查询
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        // 分页助手
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());

        // 条件查询
        Page<User> users = userDao.findByCondition(queryPageBean.getQueryString());

        // 返回一个 分页结果对象回去
        return new PageResult(users.getTotal(), users.getResult());
    }

    // 添加一个新用户
    public void add(User user,Integer[] roleIds) throws Exception {
        // 判断用户名是否已经存在
        int count = userDao.findUserCountByUsername(user.getUsername());
        if(count > 0){
            throw new Exception("用户已存在");
        }

        // 给密码加密
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));

        user.setBirthday(DateUtils.parseString2Date(DateUtils.parseDate2String(user.getBirthday())));

        // 添加用户
        userDao.add(user);
        Integer userId = user.getId();
        Map<String,Integer> map = null;
        if(roleIds != null && roleIds.length > 0){
            for (Integer roleId : roleIds) {
                map = new HashMap<>();
                map.put("userId",userId);
                map.put("roleId",roleId);
                userDao.setUserAndRole(map);
            }
        }

    }

    // 根据用户id 查询关联的角色
    public List<Integer> findRolesByUserId(Integer userId) {
        return userDao.findRolesByUserId(userId);
    }

    // 更新用户所对应的角色
    public void updateRoleAndUserId(Integer userId, Integer[] roleIds,User user) {
        System.out.println(user.getPassword());
        // 给密码加密
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
        //更新用户信息
        userDao.update(user);

        // 删除用户所对应的角色
        userDao.deleteAssocication(userId);

        // 重新建立用户所对应的角色的对应关系
        if (roleIds != null && roleIds.length > 0) {
            Map<String, Integer> map = null;
            for (Integer roleId : roleIds) {
                map = new HashMap<>();
                map.put("userId", userId);
                map.put("roleId", roleId);
                userDao.setUserAndRole(map);
            }
        }
    }

    @Override
    public void delete(Integer id){
        //先删除级联关系
        userDao.deleteUserRole(id);
        //再删除用户
        userDao.deleteUser(id);
    }

    @Override
    public User findUserById(Integer id) {
        return userDao.findUserById(id);
    }

    @Override
    public void updatePassword(Map map, String username) {
        //验证旧密码是否输入正确
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String oldPassword = (String) map.get("oldPassword");
        String password = userDao.findPasswordByUsername(username);
        boolean matches = encoder.matches(oldPassword, password);
        if(!matches){
            throw new RuntimeException("旧密码输入错误");
        }

        //比对两次密码输入是否一致
        String newPassword = (String) map.get("newPassword");
        String newPassword2 = (String) map.get("newPassword2");

        if(!newPassword.equals(newPassword2)){
            throw new RuntimeException("两次密码输入不一致");
        }else{
            //比对新密码是否与旧密码相同
            if(newPassword.equals(oldPassword)){
                throw new RuntimeException("新密码不能与旧密码相同");
            }

            userDao.updatePassword(username,encoder.encode(newPassword));
        }


    }


}
